<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/9/14 0014
 * Time: 上午 9:40
 */

namespace app\backend\controller;


use app\common\rbac;
use think\Cache;
use think\Db;

class SystemController extends BackendBase
{
	protected $protected_groupid = 8;
	protected $protected_roleid = 6;
	protected $protected_perid = 37;

	public function config()
	{
		$this->assign("title", "设置管理");
		$this->assign("name", "全局设置");
		$info = db("system_config")->value("config");
		cache("config", json_decode($info, TRUE), 86400 * 365 * 10);
		$this->assign("info", json_decode($info, TRUE));

		return $this->fetch();
	}

	public function getConfig()
	{
		$info = cache("config");
		$info['group'] = rbac::getGroupList();
		jsonReturn(1, "", $info);
	}

	public function doConfig()
	{
		$info = input("param.");
		$info['ENABLED_VERIFY'] = isset($info['ENABLED_VERIFY']) ? $info['ENABLED_VERIFY'] : "off";
		$info['DISABLED_REG'] = isset($info['DISABLED_REG']) ? $info['DISABLED_REG'] : "off";
		$info['DISABLED_INV'] = isset($info['DISABLED_INV']) ? $info['DISABLED_INV'] : "off";
		$info['DISABLED_WEB'] = isset($info['DISABLED_WEB']) ? $info['DISABLED_WEB'] : "off";
		$info['VER'] = isset($info['VER']) ? $info['VER'] : time();
		$info['KEY'] = isset($info['KEY']) ? $info['KEY'] : random();
		try {
			db("system_config")->where("config", "<>", "")->whereOr("config", "=", "")->update(["config" => json_encode($info)]);
			cache("config", $info, 86400 * 365 * 10);
			jsonReturn(1, "保存成功", cache("config"));
		} catch (\Exception $exception) {
			jsonReturn(0, "保存失败", cache("config"));
		}
	}

	public function authority()
	{
		$this->assign("title", "权限管理");
		$this->assign("name1", "用户组管理");
		$this->assign("name2", "角色管理");
		$this->assign("name3", "权限管理");

		return $this->fetch();
	}

	public function getGroupList($type = 0, $forType = 0)
	{
		$info = input("param.");
		if ($type == 0) {
			$group = rbac::getGroupList();
			if ($forType == 0) {
				unset($group[0], $group[1]);
			}
			jsonReturn(1, "", $group);
		} elseif ($type == 1) {
			$group = rbac::getRoleListFromGroupID($info['groupid'], $info['page'], $info['limit']);
			$this->jsonReturnLayUI(0, "", count(rbac::getRoleListFromGroupID($info['groupid'], 0, 10000)), $group);
		}
	}

	public function getRoleList($type = 0)
	{
		$info = input("param.");
		if ($type == 0) {
			$role = rbac::getRoleList();
			unset($role[0], $role[1]);
			jsonReturn(1, "", $role);
		} elseif ($type == 1) {
			$role = rbac::getPermissionListFromRoleID($info['roleid'], $info['page'], $info['limit']);
			$this->jsonReturnLayUI(0, "", count(rbac::getPermissionListFromRoleID($info['roleid'], 0, 10000)), $role);
		}
	}

	public function getPermissionList()
	{
		$info = input("param.");
		$permission = rbac::getPermissionList($info['page'], $info['limit']);
		$this->jsonReturnLayUI(0, "", count(rbac::getPermissionList(0, 10000)), $permission);
	}


	public function editGroup($id, $k, $v)
	{
		//用户组修改角色表
		if ($id <= $this->protected_roleid) {
			jsonReturn(0, "该用户组禁止修改");
		}
		try {
			db("user_role")->where("id", $id)->update([$k => $v]);
			jsonReturn(1, "修改成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "修改失败");
		}
	}

	public function editRole($id, $k, $v)
	{
		//角色修改权限表，权限修改权限表
		if ($id <= $this->protected_perid) {
			jsonReturn(0, "该权限禁止修改");
		}
		try {
			db("user_permission")->where("id", $id)->update([$k => $v]);
			jsonReturn(1, "修改成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "修改失败");
		}
	}

	public function delRoleGroup($array = [])
	{
		if ($array['roleid'] == 2 && $array['groupid'] == 2) {
			jsonReturn(0, "该角色禁止删除");
		}
		try {
			db("user_role_group")->where("roleid", $array['roleid'])->where("groupid", $array['groupid'])->delete();
			jsonReturn(1, "删除成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}

	public function delRolePer($array = [])
	{
		if ($array['roleid'] == 2 && $array['perid'] == 1) {
			jsonReturn(0, "该权限禁止删除");
		}
		try {
			db("user_role_permission")->where("roleid", $array['roleid'])->where("perid", $array['perid'])->delete();
			jsonReturn(1, "删除成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}

	public function delGroup($id)
	{
		if ($id <= $this->protected_groupid) {
			jsonReturn(0, "该用户组禁止删除");
		}
		try {
			rbac::delGroup($id);
			jsonReturn(1, "删除成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}

	public function delRole($id)
	{
		if ($id <= $this->protected_roleid) {
			jsonReturn(0, "该角色禁止删除");
		}
		try {
			rbac::delRole($id);
			jsonReturn(1, "删除成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}

	public function delPer($id)
	{
		if ($id <= $this->protected_perid) {
			jsonReturn(0, "该权限禁止删除");
		}
		try {
			rbac::delPermission($id);
			jsonReturn(1, "删除成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}

	public function addGroup()
	{
		$info = input("param.");
		$checkup = db("user_group")->where("name", $info['name'])->count("id");
		if ($checkup < 1) {
			try {
				db("user_group")->insert($info);
				jsonReturn(1, "新增成功");
			} catch (\Exception $exception) {
				jsonReturn(0, "新增失败");
			}
		} else {
			jsonReturn(0, "失败：名称重复");
		}
	}

	public function addRole()
	{
		$info = input("param.");
		$checkup = db("user_role")->where("name", $info['name'])->count("id");
		if ($checkup < 1) {
			try {
				db("user_role")->insert($info);
				jsonReturn(1, "新增成功");
			} catch (\Exception $exception) {
				jsonReturn(0, "新增失败");
			}
		} else {
			jsonReturn(0, "失败：名称重复");
		}
	}

	public function addPer()
	{
		$info = input("param.");
		if ($info['path'] == "*") {
			jsonReturn(0, "超管权限，全局唯一");
		} elseif (empty($info['name']) || empty($info['path']) || empty($info['status'])) {
			jsonReturn(0, "参数缺失，请重新填写");
		}
		$checkup = db("user_permission")->where("name", $info['name'])->whereOr("path", $info['path'])->count("id");
		if ($checkup < 1) {
			try {
				db("user_permission")->insert($info);
				jsonReturn(1, "新增成功");
			} catch (\Exception $exception) {
				jsonReturn(0, "新增失败");
			}
		} else {
			jsonReturn(0, "失败：名称或路径重复");
		}
	}

	public function assignRoleGroup()
	{
		//给用户组赋予角色，先删除该用户组所有角色，然后授权
		$data = $info = input("param.");
		if ($info['groupid'] == 2) {
			jsonReturn(0, "你是不是在逗我，以为我没做验证吗...？");
		}
		array_pop($data);//去除带进来的groupid
		try {
			db("user_role_group")->where("groupid", $info['groupid'])->delete();
			rbac::assignRoleGroup($info['groupid'], $data);
			jsonReturn(1, "授权成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "授权失败");
		}
	}

	public function assignRolePer()
	{
		//给角色赋予权限，先删除该角色所有权限，然后授权
		$data = $info = input("param.");
		if ($info['roleid'] == 2) {
			jsonReturn(0, "你是不是在逗我，以为我没做验证吗...？");
		}
		array_pop($data);//去除带进来的roleid
		try {
			db("user_role_permission")->where("roleid", $info['roleid'])->delete();
			rbac::assignRolePermission($info['roleid'], $data);
			jsonReturn(1, "授权成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "授权失败");
		}
	}

	public function assignUserGroup()
	{
		$info = input("param.");
		if ($info['uid'] == 1) {
			jsonReturn(0, "UID为1的用户不允许被撤销超管权限");
		}
		try {
			rbac::assignUserGroup($info['selectgroup'], $info['uid']);
			jsonReturn(1, "授权成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "授权失败");
		}
	}

	public function cache()
	{
		Cache::clear();
		$this->assign("title", "缓存管理");

		return $this->fetch();
	}

	public function smtp()
	{
		$this->assign("title", "邮件管理");
		$this->assign("name", "SMTP设置");
		$smtp = require(CONF_PATH . "extra/smtp.php");
		$this->assign("smtp", $smtp);

		return $this->fetch();
	}

	public function doSmtp()
	{
		$info = input("param.");
		if (!isset($info['secureprotocol'])) {
			$info['secureprotocol'] = "";
		}
		try {
			file_put_contents(CONF_PATH . "extra/smtp.php", "<?php\nreturn [" . "'host'=>'$info[host]','username'=>'$info[username]','password'=>'$info[password]','secureprotocol'=>'$info[secureprotocol]','port'=>'$info[port]'" . "];");
			jsonReturn(1, "成功", $info);
		} catch (\Exception $exception) {
			jsonReturn(0, "失败", $info);
		}
	}

	public function log()
	{
		$this->assign("title", "日志管理");
		$this->assign("name1", "用户日志");
		$this->assign("name2", "系统日志");

		return $this->fetch();
	}

	/**
	 * @param int $type
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\Exception
	 */
	public function getLog($type = 0)
	{
		$data = input("param.");
		$where = "";
		if (isset($data['search'])) {
			$where = [
				"content" => ["LIKE", "%$data[search]%"]
			];
		}
		if ($type == 0) {
			$count = db("user_log")->count("id");
			$info = db("user_log")->page($data['page'], $data['limit'])->order("id", "DESC")->where($where)->select();
			$this->jsonReturnLayUI(0, "", $count, $info);
		} elseif ($type == 1) {
			$count = db("log")->count("id");
			$info = db("log")->page($data['page'], $data['limit'])->order("id", "DESC")->where($where)->select();
			$this->jsonReturnLayUI(0, "", $count, $info);
		}
	}

	public function message()
	{
		$this->assign("title", "消息管理");
		$this->assign("name1", "通知管理");
		$this->assign("name2", "公告管理");
		$this->assign("name3", "提醒管理");
		$notice = db("system_config")->value("notice");
		$this->assign("notice", json_decode($notice, TRUE));

		return $this->fetch();
	}

	/**
	 * @param int $type，1 =个人通知，2=管理、反馈、举报通知3
	 *
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function getMessage($type = 1, $forType = 0)
	{
		$data = input("param.");
		$where = [
			"receiver" => ["=", session("uid")],
			"level" => ["=", $type],
			"softdel" => 0
		];
		if ($forType == 1) {
			$where = array_merge($where, ["status" => ["=", 0]]);
			$count = db("message")->where($where)->count("id");
			jsonReturn(1, "", ["count" => $count]);
		}
		$count = db("message")->where($where)->count("id");
		$info = db("message")->page($data['page'], $data['limit'])->order("id", "DESC")->where($where)->select();
		foreach ($info as $k => $v) {
			$info[$k]['from'] = getUserNameFromUID($v['sender']);
			$info[$k]['to'] = getUserNameFromUID($v['receiver']);
			$info[$k]['executor'] = empty($v['handler']) ? "" : getUserNameFromUID($v['handler']);
			$info[$k]['status'] = $v['status'] == 0 ? "未处理" : "已处理";
		}
		$this->jsonReturnLayUI(0, "", $count, $info);
	}

	public function delMessage($id)
	{
		try {
			db("message")->where("receiver", session("uid"))->whereIn("id", $id)->update(['softdel' => 1]);
			jsonReturn(1, "删除成功", ['id' => $id]);
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}

	/**
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
	public function getAnnouncement()
	{
		$data = input("param.");
		$count = db("announcement")->where("softdel", 0)->count("id");
		$info = Db::name("announcement")->page($data['page'], $data['limit'])->where("softdel", 0)->order("id", "DESC")->select();
		$this->jsonReturnLayUI(0, "", $count, $info);
	}

	public function releaseAnnouncement($content, $type = 0, $id = 0)
	{
		$str = "发布";
		try {
			$insert = [
				"content" => $content,
				"time" => nowtime()
			];
			if ($type == 0) {
				db("announcement")->insert($insert);
			} elseif ($type == 1) {
				$str = "修改";
				if (empty($id)) {
					jsonReturn(0, "参数错误");
				} else {
					db("announcement")->where("id", $id)->update(["content" => $content]);
				}
			}
			jsonReturn(1, $str . "成功");
		} catch (\Exception $exception) {
			jsonReturn(0, $str . "失败");
		}
	}

	public function delAnnouncement($id)
	{
		try {
			db("announcement")->where("id", $id)->update(['softdel' => 1]);
			jsonReturn(1, "删除成功");
		} catch (\Exception $exception) {
			jsonReturn(0, "删除失败");
		}
	}
}